package util;

import config.ApplicationConfig;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * UserRank: tum0r
 * Package Name: util
 * Time: 2019-01-25 Friday 13:26:02
 */
public class Decode {
    public String utf8Decode(String text) {
        String result = text;
        LinkedHashMap<String, String> utf8Code = ApplicationConfig.utf8Code();
        Iterator<String> iterator = utf8Code.keySet().iterator();
        String key;
        while (iterator.hasNext()) {
            key = iterator.next();
            result = result.replaceAll(utf8Code.get(key), key);
        }
        return result;
    }

    public String urlDecode(String text) {
        return urlDecode(text, "utf-8");
    }

    public String urlDecode(String text, String mode) {
        String result = text;
        try {
            result = URLDecoder.decode(result, mode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String urlUtf8Decode(String text) {
        return urlUtf8Decode(text, "utf-8");
    }

    public String urlUtf8Decode(String text, String mode) {
        return utf8Decode(urlDecode(text, mode));
    }

    public String languageDecode(String text) {
        Pattern pattern = Pattern.compile("<lang-html>(.*?)</lang-html>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(text);
        LinkedList<String> temp = new LinkedList<>();
        while (matcher.find()) {
            temp.addLast(matcher.group());
        }
        for (int i = 0; i < temp.size(); i++) {
            text = text.replace(temp.get(i), temp.get(i).replace("<lang-html>", "").replace("</lang-html>", "").replace("\r", "").replace("\n", "").trim());
        }
        return text;
    }
}
